package com.xunk.equipment.service.dnake.service;

import com.xunk.common.core.constant.DnakeConstants;
import com.xunk.common.core.enums.dnake.DnakeActionEnum;
import com.xunk.common.core.web.domain.AjaxResult;
import com.xunk.equipment.config.DnakeConfig;
import com.xunk.equipment.service.dnake.DnakePublishComponent;
import com.xunk.equipment.service.dnake.vo.DnakeCodeBindingInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ProjectName: xunk
 * @Package: com.xunk.equipment.service.dnake.service
 * @ClassName: DnakeService
 * @Author: wangtong
 * @Description: 狄耐克
 * @Date: 2021/6/10 14:06
 * @Version: 1.0
 */
@Service
@Slf4j
public class DnakeService {

    @Autowired
    private DnakeConfig dnakeConfig;

    @Autowired
    DnakePublishComponent dnakePublishComponent;

    /**
     * 根据网关sn号获取对应对码绑定信息
     *
     * @param gatewaySn 网关Sn号
     * @return
     */
    public AjaxResult getCodeBindingInfo(String gatewaySn) {
        String url;
        String port;
        try {
            String mqttHost = dnakeConfig.getMqttHost();
            url = mqttHost.substring(mqttHost.indexOf("//") + 2, mqttHost.lastIndexOf(":"));
            port = mqttHost.substring(mqttHost.lastIndexOf(":") + 1);
        } catch (Exception e) {
            return AjaxResult.error("MQTT配置mqttHost配置错误！");
        }

        DnakeCodeBindingInfoVO info = new DnakeCodeBindingInfoVO();
        info.setIotProductkey(dnakeConfig.getProductKey())
                .setIotUrl(url)
                .setIotPort(port)
                .setGwIotName(gatewaySn)
                // todo 从数据库里去
                .setGwIotSecret("");

        return AjaxResult.success(info);
    }

    /**
     * 网关上线后，app或者web调用此接口获取网关子设备
     *
     * @param gatewaySn 网关sn号
     */
    public AjaxResult getSubset(String gatewaySn) {
        try {
            dnakePublishComponent
                    .simplePublish(DnakeActionEnum.READALLDEVSTATUS.getCode(), gatewaySn, DnakeConstants.ONLINE);
        } catch (Exception e) {
            return AjaxResult.error("mqtt发布消息（获取网关子设备）失败");
        }
        // todo 待定----返回子设备吗？从数据库里查，此时已经入库

        return AjaxResult.success();
    }

}
